package com.libbase.kotlin.leetcode

class ListNode {
    var x: Int? = null
    var next: ListNode? = null

    constructor(x: Int) {
        this.x = x
    }

    constructor(x: Int, next: ListNode) {
        this.x = x
        this.next = next
    }
}

fun detectCycle(head: ListNode): Int {
    var pos = 0
    var next: ListNode? = head.next
    var isCryle = false
    while (next != null) {
        if (head.x == next.x) {
            isCryle = true
            break
        } else {
            next = next.next
        }
    }
    if (isCryle) {
        return pos
    } else {
        pos = head.next?.run {
            detectCycle(head.next!!)
        } ?: -1
        if (pos >= 0) {
            pos++
        }
    }
    return pos
}

fun main() {
    val listNode = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(4))))))
    val pos = detectCycle(listNode)
    println(pos)
}